import axios from 'axios'
import router from '@/router/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import i18n from '@/i18n'
import { ref } from 'vue'
const { t } = i18n.global
const isShow403 = ref(false)

// export const baseURL = 'https://examapi.ywhdev.cn'
export const baseURL = 'http://localhost:3000'
const instance = axios.create({
  baseURL: baseURL,
  timeout: 10000
})
/**
 * 请求拦截
 */
instance.interceptors.request.use(
  (config) => {
    const t = localStorage.getItem('t')
    if (t) {
      config.headers.setAuthorization(`Bearer ${t}`)
      config.headers.set('uid-custom-header', localStorage.getItem('uid'))
    }

    return config
  },
  (err) => {
    Promise.reject(err)
  }
)

/**
 * 响应拦截
 */
instance.interceptors.response.use(
  (res) => {
    if (res?.data.status === 401) {
      router.push('/login')
      localStorage.removeItem('uid')
      localStorage.removeItem('t')
      localStorage.removeItem('u')
      ElMessage({
        type: 'error',
        message: res.data.message || t('REQUEST.SERVER_ERROR')
      })
    } else if (res?.data.status === 404) {
      ElMessage({
        type: 'error',
        message: res.data.message || t('REQUEST.NOTFOUND')
      })
    }
    return res
  },
  (err) => {
    if (err.response?.data.status === 401) {
      router.push('/login')
      localStorage.removeItem('uid')
      localStorage.removeItem('t')
      localStorage.removeItem('u')
    } else if (err.message.split(' ')[0] === 'timeout') {
      return ElMessage.error(t('REQUEST.TIMEOUT'))
    } else if (err.code === 'ERR_BAD_REQUEST') {
      if (err.response.status === 403) {
        if (!isShow403.value) {
          isShow403.value = true
          ElMessageBox.alert('你已在别处登录，请重新登录', '登录提示', {
            showClose: false,
            callback: () => {
              router.push('/login')
              localStorage.removeItem('uid')
              localStorage.removeItem('t')
              localStorage.removeItem('u')
              isShow403.value = false
            }
          })
        }
        return Promise.reject(err)
      }
      return ElMessage({
        type: 'error',
        message: t('REQUEST.NOTFOUND')
      })
    } else if (err.code === 'ERR_NETWORK') {
      return ElMessage({
        type: 'error',
        message: t('REQUEST.SERVER_ERROR')
      })
    }

    Promise.reject(err)
  }
)

export default instance
